﻿using System;
using System.Collections;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Net;
using System.Net.Mail;


public class class_string
{
	public class_string(){		
	}

    public static string[] blackList = {"--",";--",";","/*","*/","@@","@",
                                               "char","nchar","varchar","nvarchar",
                                               "alter ","begin ","cast ","create ","cursor ","declare ","delete ","drop ","end ","exec ","execute ",
                                               "fetch"," insert "," kill ","open ",
                                               "select ", "sys ","sysobjects ","syscolumns ",
                                               "table ","update ","union ","unique ","Script","<script","<input","="};

    private static int CountSpaceChars(string stringPhamVi)
    {
        int result = 0;
        foreach (char c in stringPhamVi)
        {
            if (char.IsWhiteSpace(c))
            {
                result++;
            }
        }
        return result;
    }

    public static string clear_inject(string input)
    {
        int i = 0;
        bool output = true;
        while (i < blackList.Length && output)
        {
            if ((input.IndexOf(blackList[i], StringComparison.OrdinalIgnoreCase) >= 0))
            {
                input.Replace(blackList[i], "");
            }
            i++;
        }

        input.Replace("'", "\'");
        return input;
    }

    public static bool CheckStringInput(string parameter)
    {
        int i = 0;
        bool output = true;
        while (i < blackList.Length && output)
        {
            if ((parameter.IndexOf(blackList[i], StringComparison.OrdinalIgnoreCase) >= 0))
            {
                return  false;
            }
            i++;
        }
        return output;
    }

    // chuỗi ngẫu nhiên
    private string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    }

    int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }

    public string GetPassword()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(4, true));
        builder.Append(RandomNumber(1000, 9999));
        builder.Append(RandomString(2, false));
        return builder.ToString();
    }

    /* Mã MD5
     ---------------------------------*/
    public static string EncryptMD5(string data)
    {
        MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
        byte[] b = System.Text.Encoding.UTF8.GetBytes(data);
        b = MD5.ComputeHash(b);
        StringBuilder s = new StringBuilder();
        foreach (byte p in b)
        {
            s.Append(p.ToString("x").ToLower());
        }
        return s.ToString();


    }

    //vuvdh

    public static string MD5Hash(string text)
    {
        MD5 md5 = new MD5CryptoServiceProvider();

        //compute hash from the bytes of text
        md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));

        //get hash result after compute it
        byte[] result = md5.Hash;

        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < result.Length; i++)
        {
            //change it into 2 hexadecimal digits
            //for each byte
            strBuilder.Append(result[i].ToString("x2"));
        }

        return strBuilder.ToString();
    }

    /* Kiem tra chuoi phai la chuoi so ko
     * Chỉ tính số nguyên
     ---------------------------------*/
    public static bool IsNumberInt(string pValue) {
        foreach (Char c in pValue)
        {
            if (!Char.IsDigit(c))
                return false;
        }
        return true;
    }

    /* Kiem tra chuoi phai la chuoi so ko
     * Tính cả số thực
     ---------------------------------*/
    public static bool IsNumberFloat(string pText)
    {
        Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
        return regex.IsMatch(pText);
    }

    /*
     * --- Loại bỏ kí tự 
     */
    public static string Clear(string str)
    { 
        string result = str.Trim();
        result = result.Replace("'","\"");
        return result;
    }

    public static string clear_html(string str)
    {
        str = class_string.clear_inject(str);
        return str;
    }

    /* SEND MAIL
     ------------------------------------------------------------*/
    public static void SendMail(string from, string password, string to, string title, string content)
    {
        //Tạo đối tượng chứng thực e-mail người gửi
        NetworkCredential myEmail = new NetworkCredential(from, password);
        // Chi ra giao thức SMTP (Simple Mail Transfer Protocol) gửi mail
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.Port = 580;
        smtpClient.EnableSsl = true;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = myEmail;
        //Tạo đối tượng chứa địa chỉ người gửi và người nhận
        MailAddress fromAdd = new MailAddress(from);
        MailAddress toAdd = new MailAddress(to);
        //Tạo đối tượng chứa nội dung e-mail
        MailMessage message = new MailMessage(fromAdd, toAdd);
        //Chỉ ra thông số cho email
        message.IsBodyHtml = true;
        message.Subject = title;
        message.Body = content;
        message.Priority = MailPriority.High;
        //Gửi e-mail
        smtpClient.Send(message);
    }

    /* Kiem tra dinh dang email
     ----------------------------------------*/
    public static bool isEmail(string inputEmail)
    {
        if (inputEmail == null || inputEmail.Length == 0){
            throw new ArgumentNullException("inputEmail");
        }

        const string expression = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

        Regex regex = new Regex(expression);
        return regex.IsMatch(inputEmail);
    }

    /* Tìm kiếm
     ----------------------------------------*/
    public static string bgword(string key,string documents){
        return documents.Replace(key, "<span class='word_search'>" + key + "</span>");         
    }

    public static string TachChuoi(string Input, int Num)
    {
        string Output = string.Empty;
        int len = Input.Length;
        int n = (int)(len / Num);
        if (n > 0)
        {
            for (int i = 1; i <= n; i++)
            {
                Output += Input.Substring((i - 1) * Num, Num) + " ";
            }
            Output += Input.Substring(n * Num, len - n * Num);

        }
        else
        {
            Output = Input;
        }
        return Output;
    }

    // Ham viet hoa chu cai dau
    public static string ToFirstUpper(string _strInput)
    {
        string subStr = "";
        subStr = _strInput.Substring(0, 1).ToUpper() + _strInput.Substring(1,_strInput.Length - 1);
        return subStr;
    }
    public string BuffEncoder(string input)
    {
        byte[] buf = Encoding.ASCII.GetBytes(input);
        int l1 = buf.Length;
        int l2 = (int)l1 / 2;
        int l3 = (int)l2 / 2;
        int l4 = l1 - l2;
        for (int i = 0; i < l3; i++)
        {
            int bytevaule = Convert.ToInt32(buf.GetValue(i));
            buf.SetValue((byte)(Convert.ToInt32(buf.GetValue(l2 - 1 - i))), i);
            buf.SetValue((byte)bytevaule, l2 - 1 - i);
            bytevaule = Convert.ToInt32(buf.GetValue(i + l4));
            buf.SetValue((byte)(Convert.ToInt32(buf.GetValue(l1 - 1 - i))), l4 + i);
            buf.SetValue((byte)bytevaule, l1 - 1 - i);
        }
        for (int i = 0; i < l1; i++)
        {
            int bytevaule = 255 - Convert.ToInt32(buf.GetValue(i));
            buf.SetValue((byte)bytevaule, i);
        }
        string output = Convert.ToBase64String(buf);
        buf.Clone();
        return output;
    }
    //--------------------------------------------------------------------------------------------------

    //----Giải mã chuỗi--------------------------------------------------------------------------------
    public string BuffDecoder(string input)
    {
        try
        {
            byte[] buf = Convert.FromBase64String(input);
            int l1 = buf.Length;
            int l2 = (int)l1 / 2;
            int l3 = (int)l2 / 2;
            int l4 = l1 - l2;
            for (int i = 0; i < l1; i++)
            {
                int bytevaule = 255 - Convert.ToInt32(buf.GetValue(i));
                buf.SetValue((byte)bytevaule, i);
            }
            for (int i = 0; i < l3; i++)
            {
                int bytevaule = Convert.ToInt32(buf.GetValue(i));
                buf.SetValue((byte)(Convert.ToInt32(buf.GetValue(l2 - 1 - i))), i);
                buf.SetValue((byte)bytevaule, l2 - 1 - i);
                bytevaule = Convert.ToInt32(buf.GetValue(i + l4));
                buf.SetValue((byte)(Convert.ToInt32(buf.GetValue(l1 - 1 - i))), l4 + i);
                buf.SetValue((byte)bytevaule, l1 - 1 - i);
            }
            string report = Encoding.ASCII.GetString(buf);
            buf.Clone();
            return report;
        }
        catch (Exception ex)
        {
            return null;
        }

    }
    public string ConvertToHtmlTag(string input)
    {
        string output = "";
        output = input.Replace("&lt;", "<");
        output = input.Replace("&gt;", ">");
        return output;
    }

}
